package thread;

/**
 * @author liweimin
 * @date 2021/3/5 14:49
 * @description 生产者、消费者
 */
public class ProducerAndConsumer {
    public static void main(String[] args) {

//        Stock stock = new Stock();
//
//        Producer producer = new Producer(stock);
//        Consumer consumer = new Consumer(stock);
//
//        Thread thread1 = new Thread(producer);
//        Thread thread2 = new Thread(consumer);
//
//        thread1.start();
//        thread2.start();
        Stock stock = new Stock();
        Thread producerThread = new Thread(new Producer(stock));
        Thread consumerThread = new Thread(new Consumer(stock));

        producerThread.start();
        consumerThread.start();
    }

}


/**
 * 生产者
 */
class Producer implements Runnable {
    Stock stock;

    public Producer(Stock stock) {
        this.stock = stock;
    }

    @Override
    public void run() {
        System.out.println("生产者开始生产产品");
        while (true) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            stock.produceOne("联想");
        }
    }
}

/**
 * 消费者
 */
class Consumer implements Runnable {
    Stock stock;

    public Consumer(Stock stock) {
        this.stock = stock;
    }

    @Override
    public void run() {

        while (true) {
            System.out.println("消费者开始消费产品");
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            stock.consumeOne();
        }
    }
}

/**
 * 库存
 */
class Stock {
    private String name;
    /**
     * 库存容量
     */
    private int count = 0;

    public synchronized void produceOne(String name) {
        while (count >= 10) {
            try {
                wait();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        this.name = name;
        count++;
        System.out.println("生产者...生产了 " + name + "库存还有" + count);
        notifyAll();

    }

    public synchronized void consumeOne() {
        while (count <= 0) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        count--;
        System.out.println("消费者...消费了 " + name + "库存还有" + count);
        notifyAll();

    }
}